import _ from 'lodash';
import { ZoneProxy } from '../proxy';

export async function zoneRequired(req, res, next) {
  const appId = res.locals.appId;
  const zoneId = req.query.zoneId || req.body.zoneId || req.params.zoneId;
  if (!zoneId) return next();

  let doc = await ZoneProxy.findOneById(appId, zoneId);
  doc.href = 'zone/' + doc.key + '/' +  doc.template + '?appId=' + appId + '&zoneId=' + doc._id;

  if(doc) {
    res.locals.zone = doc;
  }

  next();
}

export async function zonesRequired(req, res, next) {
  const appId = res.locals.appId;
  const docs = await ZoneProxy.find(appId, {deleted: false, enable: true });

  docs.forEach(function(doc) {
    doc.href = 'zone/' + doc.key + '/' +  doc.template + '?appId=' + appId + '&zoneId=' + doc._id;
  });

  if(docs) {
    res.locals.zones = docs;
    res.locals.navs = docs;
  }

  next();
}
